package utils;

import java.io.File;
import java.math.BigDecimal;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;

import org.apache.commons.lang.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;















import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;

import play.cache.Cache;
import play.libs.Codec;
import play.libs.Files;
import redis.clients.jedis.Jedis;
import services.CaseService;
import services.CourtLiveService;
import services.DrMicroService;
import models.DrCase;
import models.DrLiveTemp;
import models.DrMicrophone;

/**
 * 同步数据线程
 * @author wangshaoming
 *
 */
public class SysnDataThread implements Runnable{
	public static final Logger log=LoggerFactory.getLogger("thread");
	private String caseid;
	private String courtid;
	public SysnDataThread(String caseid,String courtid){
		this.caseid=caseid;
		this.courtid=courtid;
	}
	//执行
	public void run(){
		while(true){
			try{
				//从缓存中获取法庭状态
				BigDecimal status=(BigDecimal)Cache.get(this.caseid+BizConstants.CACHE_CASE_STATUS);
				if(status==null){
					DrCase cases=CaseService.getById(this.caseid);
					if(cases==null){
						continue;
					}
					Cache.set(caseid+BizConstants.CACHE_CASE_STATUS, cases.getStatus());
					if(!new BigDecimal(1).equals(cases.getStatus())){
						break;
					}
				}
				else if(!BizConstants.CASE_STATUS_START.equals(status)){
					Cache.safeDelete(this.caseid+BizConstants.CACHE_CASE_STATUS);
					Cache.safeDelete(this.caseid+BizConstants.CACHE_CASE_KEY);
					Cache.safeDelete(this.caseid+BizConstants.CACHE_CASE_ISUPDATE);
					break;
				}
				log.info("----------------转写开始-------------------------");
				//读取redis
				Jedis jedis= RedisUtil.getJedis();
				//取出第一条并删除redis的第一条
				String lastOne="";
				try{
					lastOne=jedis.lpop(this.caseid);
				}catch(Exception e){
					e.printStackTrace();
				}finally{
					RedisUtil.returnResource(jedis);
				}
				if(StringUtils.isNotEmpty(lastOne)){
					log.info("读取后："+lastOne);
				}
				else{
					continue;
				}
				//解析redis中读取的数据
				DrLiveTemp temp=null;
				try{
					temp=JSONObject.parseObject(lastOne, DrLiveTemp.class);
				}catch(Exception e){
					log.error("--------------转json错误"+lastOne);
					e.printStackTrace();
				}
				if(temp==null){
					continue;
				}
				if(temp.getBeginTime()==null){
					continue;
				}
				//获取讲话人角色
				DrMicrophone phone=DrMicroService.getById(temp.getRole());
				if(phone==null){
					continue;
				}
				temp.setRolename(phone.getStaffrole());
				//获取最后一个节点
				DrLiveTemp lasttemp=new DrLiveTemp();
				String cacheLashOne=(String)Cache.get(this.caseid+BizConstants.CACHE_CASE_KEY);
				if(StringUtils.isEmpty(cacheLashOne)){
					lasttemp=CourtLiveService.getLastOne(this.caseid);
					if(lasttemp!=null){
						log.info("最后一个节点："+JSONObject.toJSONString(lasttemp));
						Cache.set(this.caseid+BizConstants.CACHE_CASE_KEY, JSONObject.toJSONString(lasttemp));
					}
				}else{
					lasttemp=(DrLiveTemp)JSONObject.parseObject(cacheLashOne, DrLiveTemp.class);
				}
				if(lasttemp==null){
					temp.setCaseid(this.caseid);
					temp.setTempid(Codec.UUID());
					temp.setCreatetime(new Date());
					CourtLiveService.insertTemp(temp);
					Cache.set(this.caseid+BizConstants.CACHE_CASE_KEY, JSONObject.toJSONString(temp));
					//将最后一条的开始时间戳加入缓存，用于页面轮询判断是否查询数据库
					Cache.set(this.caseid+BizConstants.CACHE_CASE_ISUPDATE, temp.getBeginTime());
					log.info("插入后："+lastOne);
				}
				else{
					if(temp.getBeginTime().longValue()==lasttemp.getBeginTime().longValue()){
						lasttemp.setCreatetime(new Date());
						lasttemp.setEndTime(temp.getEndTime());
						lasttemp.setRolename(temp.getRolename());
						lasttemp.setRole(temp.getRole());
						lasttemp.setText(temp.getText());
						lasttemp.setCaseid(this.caseid);
						CourtLiveService.updateTemp(lasttemp);
						Cache.set(this.caseid+BizConstants.CACHE_CASE_KEY, JSONObject.toJSONString(lasttemp));
						//相同的开始时间戳在时间后加1表示已更新
						Cache.set(this.caseid+BizConstants.CACHE_CASE_ISUPDATE, temp.getBeginTime().add(new BigDecimal(1)));
						log.info("更新后："+lastOne);
					}
					else{
						temp.setTempid(Codec.UUID());
						temp.setCaseid(this.caseid);
						temp.setCreatetime(new Date());
						CourtLiveService.insertTemp(temp);
						Cache.set(this.caseid+BizConstants.CACHE_CASE_KEY, JSONObject.toJSONString(temp));
						Cache.set(this.caseid+BizConstants.CACHE_CASE_ISUPDATE, temp.getBeginTime());
						log.info("插入后："+lastOne);
					}
				}
				
			}catch(Exception e){
				e.printStackTrace();
				log.info("--------------转写失败--------------------");
			}
			//三秒后继续读写
			try {
				log.info("----------------转写结束-------------------------");
				Thread.sleep(100);
			} catch (InterruptedException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			}
		}
	}
}
